package com.software.car.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.software.car.api.FileSavaService;
import com.software.car.common.enums.ResultEnum;
import com.software.car.common.exception.MyException;
import com.software.car.common.utils.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * 配置阿里云对象存储库，来实现文件保存服务
 *
 * @Author 魔法はまだ解けない
 * @Date 2021/2/16
 */
@Service
public class OssServiceImpl implements FileSavaService {

    @Value("${oos.endpoint}")
    private String endpoint;
    @Value("${oos.accessKeyId}")
    private String accessKeyId;
    @Value("${oos.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oos.bucketName}")
    private String bucketName;
    @Value("${oos.path}")
    private String path;
    @Value("${user.avatarPrefix}")
    private String avatarPrefix;


    /**
     * 设置url过期时间为：1分钟
     */
    Date expiration = new Date(System.currentTimeMillis() + 60 * 1000);

    /**
     * 初始化阿里云获取数据对象
     *
     * @return
     */
    private OSS init() {
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 设置是否支持CNAME。CNAME用于将自定义域名绑定到目标Bucket。
        conf.setSupportCname(true);
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);
        return ossClient;
    }

    @Override
    public String uploadFile(MultipartFile multipartFile) throws IOException {
        OSS ossClient = init();
        InputStream inputStream = multipartFile.getInputStream();
        //拼接阿里云存储名称
        String originalFilename = SnowflakeIdGenerator.getId() + multipartFile.getOriginalFilename();
        if (originalFilename.length() > 1024) {
            throw new MyException(ResultEnum.EXCEPTION);
        }
        ossClient.putObject(bucketName, path + originalFilename, inputStream);
        ossClient.shutdown();
        return avatarPrefix+originalFilename;
    }

    @Override
    public String uploadFileNew(MultipartFile multipartFile) throws IOException {
        String orginalFilename=multipartFile.getOriginalFilename();//获取文件的名称
        String flag= IdUtil.fastSimpleUUID();  //生成一个随机标识
        String rootFilePath=System.getProperty("user.dir")+"/src/main/resources/files/"+flag+"_"+orginalFilename;
        FileUtil.writeBytes(multipartFile.getBytes(),rootFilePath);
        return "http://116.62.247.153:8091/photoload/"+flag;
    }

    @Override
    public void getFile(String fileName, HttpServletResponse response) throws IOException {
        //拼接名称
        fileName = path + fileName;
        OSS ossClient = init();
        OSSObject ossObject = ossClient.getObject(bucketName, fileName);

        InputStream objectContent = ossObject.getObjectContent();


        ServletOutputStream outputStream = response.getOutputStream();
        /**
         * 将阿里云获取的流数据传输至response中
         */
        byte b[] = new byte[1024];
        int ken;
        while ((ken = objectContent.read(b)) != -1) {
            outputStream.write(b, 0, ken);
        }
        outputStream.close();
        objectContent.close();

        ossClient.shutdown();
    }

    @Override
    public void deleteFreeFile() {

    }
}
